package com.qf.zyh.dao.Impl;

import com.qf.zyh.dao.ProductDao;
import com.qf.zyh.entity.Product;
import com.qf.zyh.entity.Type;
import com.qf.zyh.util.DBUtil;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

public class ProductDaoImpl implements ProductDao {
    QueryRunner qr = new QueryRunner();
    @Override
    public List<Product> getall(Integer tid) {
        try {
            return qr.query(DBUtil.getConnection(),"select pid,tid,pname,ptime,pimage,pprice,pstate,pinfo from product where tid=?",new BeanListHandler<>(Product.class),tid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Product getid(Integer pid) {
        try {
            //map中封装为列名=数据
            Map<String, Object> query = qr.query(DBUtil.getConnection(), "select p.pid,p.tid,p.pname,p.ptime,p.pimage,p.pprice,p.pstate,p.pinfo,t.tname,t.tinfo FROM product p,type t where p.tid=t.tid AND pid=?",
                    new MapHandler(), pid);
            //首先创建两个对应的对象
            if(query!=null){
                Product pro=new Product();
                Type type = new Type();
                //工具类方法为，传入需要封装的对象和map中的数据集合。会根据key值将对应数据进行set设值
                BeanUtils.populate(pro,query);
                BeanUtils.populate(type,query);
                //最后将type的值设值到pro中
                pro.setType(type);
                return pro;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return null;
    }
    //对应数据的总条数
    @Override
    public Long countid(Integer tid) {
        try {
            return qr.query(DBUtil.getConnection(),"select count(pid) from product where tid=?",new ScalarHandler<>(),tid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public List<Product> selectpage(Integer tid, int pageIndex, int pageSize) {
        try {
            return qr.query(DBUtil.getConnection(),"select pid,tid,pname,ptime,pimage,pprice,pstate,pinfo from product where tid=? limit ?,?",new BeanListHandler<>(Product.class),tid,pageIndex,pageSize);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
}
